<template>
  <div class="search-suggestion">
    <van-cell
      icon="search"
      :title="item"
      v-for="(item, index) in suggestions"
      :key="index"
      @click="$emit('search',item)"
    >
      <div slot="title" v-html="highlight(item)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from "@/API/search";
import { debounce } from "lodash";
export default {
  name: "SearchSuggestion",
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      suggestions: [], //联想建议数据列表
    };
  },
  watch: {
    searchText: {
    //通过防抖来解决输入过快
    handler: debounce(async function () {
      const { data } = await getSearchSuggestions(this.searchText);
      this.suggestions = data.data.options;
    }, 200),
    immediate: true,
  }
  },
  methods: {
    highlight(str) {
    return  str.replace(
        new RegExp(this.searchText, "gi"),
        `<span style="color:red">${this.searchText}</span>`
      );
    },
  },
};
</script>

<style>
</style>